package ogmios.processes;

import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import java.lang.reflect.*;
import ogmios.core.*;

/**
 * A thread that will write the contents of an input stream into a JTextComponent
 */
public class DefaultInputThread extends Thread
{
    public Document deposit;
    protected BufferedReader input;
    protected InputStream in;
    protected Runnable updater;
    protected int bufferSize;
    protected char[] buffer = new char[1024];
    public DefaultInputThread(JTextComponent newDeposit, InputStream stream)
    {
        deposit = newDeposit.getDocument();
        input = new BufferedReader(new InputStreamReader(stream));
        updater = new Runnable()
        {
            public void run()
            {
                try
                {
                    deposit.insertString(deposit.getLength(), new String(buffer, 0, bufferSize), null);
                }
                catch (BadLocationException ble)
                {
                }
            }
        };
        setDaemon(true);
    }

    public void run()
    {
//int length;
        try
        {

            while ((bufferSize = input.read(buffer, 0, 1024)) != -1)
            {

                SwingUtilities.invokeAndWait(updater);

            }

            input.close();
        }
        catch (InterruptedException e)
        {
            OgmiosUtilities.showErrorBox(null, e, "Process:Input Error");
        }
        catch (InvocationTargetException e)
        {
            OgmiosUtilities.showErrorBox(null, e, "Process:Input Error");
        }
        catch (IOException ex)
        {
            OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
        }
        catch (Throwable ex)
        {
            OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
        }
    }
}
